package com.weblog.weblogapi.handler;

import com.alibaba.fastjson.JSON;
import com.weblog.weblogapi.dao.pojo.User;
import com.weblog.weblogapi.service.UserService;
import com.weblog.weblogapi.utils.JWTUtils;
import com.weblog.weblogapi.vo.ErrorCode;
import com.weblog.weblogapi.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String token = request.getHeader("token");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");


        if(StringUtils.isAllBlank(token)){
            Result result=Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        Map<String, Object> stringObjectMap= JWTUtils.checkToken(token);
        if(stringObjectMap==null){
            return false;
        }
        User user=userService.findUserById((String) stringObjectMap.get("user"));
        if(user==null){
            Result result=Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
//        UserThreadLocal.put(sysUser);
        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserThreadLocal.remove();
//    }
}
